/** @type {HTMLCanvasElement} */
const canvas = document.getElementById('canvasEle')
const audioEle = document.getElementById('aduioEle')

const ctx = canvas.getContext('2d')

function CanvasInit () {
  canvas.width = 1500
  canvas.height = 550
  // canvas.style.border = '1px solid red'
}
CanvasInit()



let isInit = false
let Analyser, dataArray
audioEle.addEventListener('play', () => {
  if (isInit) return null
  // // 初始化操作
  const audCtx = new AudioContext()
  const source = audCtx.createMediaElementSource(audioEle)
  Analyser = audCtx.createAnalyser()
  // // 设置分析器
  Analyser.fftSize = 512 //必须时2的n次方
  // //准备好 一个数组容器 注意 这是 一个每一项 为一个8位(一字节 8个01)的无符号整数 (-127  - 128)
  const ArraySize = Analyser.frequencyBinCount //相当于 512/2 因为 傅里叶变换是对称的
  dataArray = new Uint8Array(ArraySize)

  source.connect(Analyser)
  Analyser.connect(audCtx.destination)

  isInit = true
  draw()
  // console.log('play')
})

function Getrandom_0toparams (params) {
  return Math.floor(Math.random() * params)
}
function getrandomStyle () {
  const one = `#${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}C${Getrandom_0toparams(10)}f${Getrandom_0toparams(10)}`
  const two = `#${Getrandom_0toparams(10)}f${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}`
  const three = `#fe${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}${Getrandom_0toparams(10)}`

  return Getrandom_0toparams(3) === 0 ? one : (Getrandom_0toparams(3) === 1 ? two : three)
}
// 绘制
function draw () {

  requestAnimationFrame(draw)
  const { width, height } = canvas
  if (!isInit) return null
  // 先清理
  ctx.clearRect(0, 0, width, height)
  // 开画
  // 拿数据
  Analyser.getByteFrequencyData(dataArray)
  const len = dataArray.length / 1.1
  const barWidth = width / len
  for (let i = 0; i < len; i++) {
    const barHeight = dataArray[i] / 255 * height
    const x1 = i * barWidth + width / 2
    const x2 = width / 2 - ((i + 1) * barWidth)
    const y = height - barHeight
    ctx.fillStyle = getrandomStyle() //'#78C5F7'

    ctx.fillRect(x1, y, barWidth - 1, barHeight)
    ctx.fillRect(x2, y, barWidth - 1, barHeight)
  }
  // dataArray.forEach()


}

// function Init () {
//   if (!isInit) return null
//   const souce = audio.


//     isInit = true
// }
// Init()

// console.log(ctx)